<template>
  <a-upload
    :action="action"
    :headers="{
      'Authorization': `Bearer ${token}`,
      'tenantId': tenantId
    }"
    :name="name"
    :file-list="image ? [image] : []"
    :draggable="draggable"
    :accept="accept"
    :show-file-list="false"
    @change="handleChange"
  >
    <template #upload-button>
      <div
        class="arco-upload-list-item"
      >
        <div
          v-if="image"
          class="arco-upload-list-picture custom-upload-avatar"
        >
          <img :src="image?.status === 'done'? image?.response?.data?.url: image?.url" />
          <div class="arco-upload-list-picture-mask">
            <icon-loading v-if="image?.status === 'uploading'"/>
            <IconEdit v-else/>
          </div>
        </div>
        <div
          v-else-if="modelValue"
          class="arco-upload-list-picture custom-upload-avatar"
        >
          <img :src="modelValue" />
          <div class="arco-upload-list-picture-mask">
            <IconEdit />
          </div>
        </div>
        <div v-else class="arco-upload-picture-card">
          <div class="arco-upload-picture-card-text">
            <IconPlus />
          </div>
        </div>
      </div>
    </template>
  </a-upload>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { getToken } from "@/utils/auth";
import { getTenantId } from "@/utils/tenant";
import type { FileItem } from "@arco-design/web-vue/es/upload/interfaces";
import { uploadPath } from "@/api/modules/oss";

defineProps({
  action: {
    type: String,
    required: false,
    default: () => uploadPath
  },
  name: {
    type: String,
    required: false,
    default: 'file'
  },
  accept: {
    type: String,
    required: false,
    default: 'image/*'
  },
  disabled: {
    type: Boolean,
    required: false,
    default: false
  },
  modelValue: {
    type: String,
    required: true
  },
  draggable: {
    type: Boolean,
    default: false
  }
})

const token = getToken()
const tenantId = getTenantId()
const image = ref<FileItem>()
const emit = defineEmits(['update:modelValue']);


const handleChange = (_: FileItem[], fileItem: FileItem) => {
  image.value = fileItem
  if (image.value?.status === 'done') {
    emit('update:modelValue', image.value?.response?.data?.url)
  } else if (image?.value?.status === 'error') {
    image.value.url = undefined
    emit('update:modelValue', undefined)
  }
}


</script>

<script lang="ts">
export default {
  name: "ESingleImageUpload"
};
</script>

<style scoped>

</style>
